import socket
import psutil
import sys


def get_local_ip():
    ips = get_all_ipv4_addrs()
    if len(ips) == 0:
        return "127.0.0.1"
    return ips[0]


def get_all_ipv4_addrs():
    ipv4_addrs = []
    virtual_keywords = ["virtual", "vm", "veth"]  # 不太靠谱
    for name, addrs in psutil.net_if_addrs().items():
        is_virtual = False
        for keyword in virtual_keywords:
            if keyword in name.lower():
                is_virtual = True
                break

        if is_virtual:
            continue

        ipv4s = [
            addr.address
            for addr in addrs
            if addr.family == socket.AF_INET
            and not addr.address.startswith("169.254")
            and addr.address != "127.0.0.1"
        ]
        ipv4_addrs.extend(ipv4s)
    return ipv4_addrs


def is_linux():
    return (
        sys.platform.lower().find("linux") != -1
        or sys.platform.lower().find("darwin") != -1    # macOS归为linux
    )


def is_windows():
    return sys.platform.lower().find("win32") != -1
